package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.activity.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;


    @Override
    public List<Activity> getByType(Integer type) {
        return activityMapper.selectByType(type);
    }


    @Override
    public void updateActivity(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.update(activity);
    }

    @Override
    public Activity getById(Integer id) {
        return activityMapper.select(id);
    }


    @Override
    public void deleteById(Integer id) {
        activityMapper.delete(id);
    }

    @Override
    public void addActivity(Activity activity) {
        boolean hasNull = BeanUtil.hasNullField(activity, "id", "discount", "voucher", "createTime", "updateTime");
        if (hasNull) {
            throw new RuntimeException("参数错误");
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.insert(activity);
    }


    @Override
    public PageResult<Activity> list(ActivityDTO activityDTO) {
        // 开始分页
        PageHelper.startPage(activityDTO.getPage(), activityDTO.getPageSize());

        // 执行查询
        List<Activity> activities = activityMapper.selectActivities(activityDTO);

        //status  1-未开始  2- 进行中   3-已结束
        if (activityDTO.getStatus() != null) {
            Iterator<Activity> iterator = activities.iterator();
            LocalDateTime now = LocalDateTime.now();
            while (iterator.hasNext()) {
                Activity activity = iterator.next();
                if (activity.getStartTime() == null || activity.getEndTime() == null) {
                    iterator.remove();
                    continue;
                }
                int time = 0;
                if (activity.getStartTime().compareTo(now) > 0) {
                    time = 1;
                } else if (activity.getStartTime().compareTo(now) <= 0 && activity.getEndTime().compareTo(now) > 0) {
                    time = 2;
                } else {
                    time = 3;
                }
                if (time != activityDTO.getStatus()) iterator.remove();
            }
        }


        // 获取分页信息
        Page<Activity> pageInfo = (Page<Activity>) activities;

        // 封装成 PageResult 对象
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getResult());
    }

}
